﻿using Microsoft.Win32;
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Data;
using System.Diagnostics;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Interop;
using System.Windows.Media.Animation;
using System.Windows.Threading;
using Utility;
using ViewModel;

namespace SteelDetection
{
    /// <summary>
    /// App.xaml 的交互逻辑
    /// </summary>
    public partial class App : Application
    {
        public Mutex Mutex;
        public App()
        {
            SingleInstanceCheck();
        }
        protected override void OnStartup(StartupEventArgs e)
        {

            VM_WindowMain vm = VM_WindowMain.GetInstance();
            Application.Current.MainWindow = vm.UIElement as Window;
            vm.Show();

            System.Drawing.Text.InstalledFontCollection ifc = new System.Drawing.Text.InstalledFontCollection();
            if (ifc.Families.Where(t => t.Name == "iconfont").Count() == 0)
            {
                MessageBox.Show("缺少缺陷图标字体，点击确定后会弹出字体安装界面，请点击“安装”按钮进行安装");

                System.Diagnostics.Process.Start(Environment.CurrentDirectory + @"\Image\Resources\font\iconfont.ttf");

            }
            Timeline.DesiredFrameRateProperty.OverrideMetadata(
                typeof(Timeline), new FrameworkPropertyMetadata { DefaultValue = 25 });

            base.OnStartup(e);
        }

        protected override void OnLoadCompleted(System.Windows.Navigation.NavigationEventArgs e)
        {
            base.OnLoadCompleted(e);
            Current.DispatcherUnhandledException += App_OnDispatcherUnhandledException;
            AppDomain.CurrentDomain.UnhandledException += CurrentDomain_UnhandledException;
            SystemEvents.SessionSwitch += SystemEvents_SessionSwitch;
        }

        //尝试解决远程问题
        private void SystemEvents_SessionSwitch(object sender, Microsoft.Win32.SessionSwitchEventArgs e)
        {
            if (e.Reason == SessionSwitchReason.RemoteDisconnect || e.Reason == SessionSwitchReason.ConsoleDisconnect)
            {
                //Application.Current.MainWindow.
            }
        }

        /// <summary>
        /// UI线程抛出全局异常事件处理
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void App_OnDispatcherUnhandledException(object sender, DispatcherUnhandledExceptionEventArgs e)
        {
            try
            {
                e.Handled = true;
                Logger.Error(e.Exception);
            }
            catch (Exception ex)
            {

            }
        }

        /// <summary>
        /// 非UI线程抛出全局异常事件处理
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void CurrentDomain_UnhandledException(object sender, UnhandledExceptionEventArgs e)
        {
            try
            {
                var exception = e.ExceptionObject as Exception;
                if (exception != null)
                {
                    Logger.Error(exception);
                }
            }
            catch (Exception ex)
            {


            }
        }

        public void SingleInstanceCheck()
        {

            bool isOnlyInstance = false;
            Mutex = new Mutex(true, @"SteelDetectClient", out isOnlyInstance);
            if (!isOnlyInstance)
            {
                //ActivateExistingInstance();
                // this exits the application
                Environment.Exit(0);
            }

        }
        private static void ActivateExistingInstance()
        {
            // 尝试打开互斥体
            Mutex mutex = Mutex.OpenExisting("SteelDetectClient");

            // 获取互斥体对应的窗口句柄
            IntPtr hWnd = mutex.SafeWaitHandle.DangerousGetHandle();
            
            // 获取窗口句柄对应的 WPF 窗口
            Window wpfWindow = Application.Current.Windows.OfType<Window>().FirstOrDefault(w => new WindowInteropHelper(w).Handle == hWnd);
            MessageBox.Show(wpfWindow != null?"找到了":"没找到");
            // 如果找到了 WPF 窗口，激活它
            if (wpfWindow != null)
            {
                wpfWindow.WindowState = WindowState.Normal;
                wpfWindow?.Activate();
            }


        }
    }
}
